// src/main/java/com/dongdong/zhuangji/config/ResourceServerConfig.java
package com.dongdong.zhuangji.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource(name = "tokenStore") // 引用TokenConfig中定义的TokenStore
    private TokenStore tokenStore;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
                .and()
                .authorizeRequests()
                // 需要认证的路径（与WebSecurityConfig中的配置一致）
                .antMatchers("/pileData/**", "/controlPoints/**")
                .authenticated()
                .anyRequest()
                .permitAll()
                .and()
                .csrf().disable(); // 禁用CSRF（适用于API场景）
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .tokenStore(tokenStore) // 使用JwtTokenStore解析令牌
                .resourceId("pileData"); // 配置资源ID，需与AuthorizationServer中的resourceIds一致
    }
}